package com.etc.bridgedataanalysis.config;

import com.etc.bridgedataanalysis.service.Bridge;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.stereotype.Component;

import java.io.*;
import java.sql.SQLException;
import java.text.ParseException;

@Slf4j
@Component
public class FileListener implements FileAlterationListener {


    @Override
    public void onStart(FileAlterationObserver observer) {
        System.out.println("观察文件变化任务开始");
    }

    @Override
    public void onDirectoryCreate(File directory) {
        System.out.println("创建文件夹" + directory);
    }

    @Override
    public void onDirectoryChange(File directory) {
        System.out.println("创建文件夹" + directory);
    }

    @Override
    public void onDirectoryDelete(File directory) {
        System.out.println("删除文件夹" + directory);
    }

    @Override
    public void onFileCreate(File file) {
        log.info("[新建]:" + file.getAbsolutePath());

        try {
            Bridge.insert(file.getAbsolutePath());
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFileChange(File file) {
        log.info("[修改]:" + file.getAbsolutePath());
        BufferedReader buf = null;
        try {
            buf = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
            BufferedReader br = new BufferedReader(buf);
            String line = null;
            System.out.println(br.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 这里释放系统 IO 资源
            try {
                if (buf != null) {
                    buf.close();
                }
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onFileDelete(File file) {
        System.out.println("删除文件" + file);
    }

    @Override
    public void onStop(FileAlterationObserver observer) {
        System.out.println("观察文件变化任务结束");
    }
}
